﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.采购管理.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.采购管理
{
    public partial class Quality : Form
    {
        public Quality()
        {
            InitializeComponent();
            // 使用Load事件来确保窗体完全加载后再加载数据
            this.Load += Quality_Load;
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void Quality_Load(object sender, EventArgs e)
        {
            LoadInspectionDepartments();
        }

        /// <summary>
        /// 加载质检部门数据到下拉框
        /// </summary>
        private async void LoadInspectionDepartments()
        {
            try
            {
                // 显示加载状态
                QuaDepId.Items.Clear();
                QuaDepId.Items.Add("正在加载...");
                QuaDepId.Enabled = false;

                using (HttpClient client = new HttpClient())
                {
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    HttpResponseMessage response = await client.GetAsync("http://localhost:5117/api/Supplier/GetInspectionDepInfo");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string jsonResult = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API返回的JSON数据: {jsonResult}");
                        
                        var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<DepInsop>>>(jsonResult);
                        
                        if (apiResponse != null && apiResponse.Data != null && apiResponse.Code == 200)
                        {
                            QuaDepId.Items.Clear();
                            QuaDepId.DisplayMember = "InsDepName";
                            QuaDepId.ValueMember = "InsDepId";
                            
                            // 添加默认选项
                            QuaDepId.Items.Add(new DepInsop { InsDepId = 0, InsDepName = "请选择部门" });
                            
                            foreach (var dept in apiResponse.Data)
                            {
                                QuaDepId.Items.Add(dept);
                                Console.WriteLine($"添加部门: ID={dept.InsDepId}, Name={dept.InsDepName}");
                            }
                            
                            // 默认选中第一个选项（请选择部门）
                            QuaDepId.SelectedIndex = 0;
                            
                            // 显示加载成功的消息
                            Console.WriteLine($"成功加载 {apiResponse.Data.Count} 个质检部门");
                            MessageBox.Show($"成功加载 {apiResponse.Data.Count} 个质检部门", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            QuaDepId.Items.Clear();
                            QuaDepId.Items.Add("加载失败");
                            MessageBox.Show($"加载质检部门数据失败: {apiResponse?.Msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        QuaDepId.Items.Clear();
                        QuaDepId.Items.Add("HTTP请求失败");
                        MessageBox.Show($"HTTP请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                QuaDepId.Items.Clear();
                QuaDepId.Items.Add("加载异常");
                MessageBox.Show($"加载质检部门数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"异常详情: {ex}");
            }
            finally
            {
                QuaDepId.Enabled = true;
            }
        }

        /// <summary>
        /// 添加的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddQur_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取选中的部门ID
                int selectedDepId = 0;
                if (QuaDepId.SelectedItem != null)
                {
                    var selectedDept = QuaDepId.SelectedItem as DepInsop;
                    selectedDepId = selectedDept?.InsDepId ?? 0;
                }

                var Add = new PlanDatas
                {
                    quaCode = QuaCode.Text.Trim(),
                    qIName = QuaName.Text.Trim(),
                    qualityInspector = QualityInspector.Text.Trim(),
                    quaState = false,
                    quaDepId = selectedDepId,
                    //时间类型转化
                    quaDate = DateTime.Parse(QuaDate.text),
                    quaName = QuaName.Text.Trim(),
                    lDate = DateTime.Parse(LDate.text),
                };
                string jsonData = JsonConvert.SerializeObject(Add);
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync("http://localhost:5117/api/Qulity/AddQuality", content);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("质检信息添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        ClearForm();
                    }
                    else
                    {
                        MessageBox.Show("质检信息添加失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加质检信息时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重置的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelQur_Click(object sender, EventArgs e)
        {
            ClearForm();
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            QuaCode.Text = "";
            QuaName.Text = "";
            QualityInspector.Text = "";
            QuaDepId.SelectedIndex = -1;
            QuaDate.text = DateTime.Now.ToString("yyyy-MM-dd");
            LDate.text = DateTime.Now.ToString("yyyy-MM-dd");
            QuaRemark.Text = "";
        }
    }

    /// <summary>
    /// API响应模型 - 根据实际API响应结构调整
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ApiResponse<T>
    {
        public string Msg { get; set; }
        public int Code { get; set; }
        public T Data { get; set; }
        public object Datas { get; set; }
    }
}
